import { syncDiyField } from "../utils/diy_field-sync.js";
import { syncSysMenu } from "../utils/sys_menu-sync.js";
import {
  getSourceDiyTable,
  syncDiyTableMetadata,
  checkTargetTableExists,
  createTableInTarget,
  syncTableDataOnce,
  compareAndSyncTableSchema,
} from "../utils/db-sync-utils.js";

export async function migrateTable(sourceConn, targetConn, tableName, { removeField = false, isDeleteRedundant = false, sqlLogs = [] }) {
  // 同步 diy_table
  const sourceTable = await getSourceDiyTable(sourceConn, tableName);
  const diyTable = await syncDiyTableMetadata(sourceConn, targetConn, sourceTable, tableName);
  console.log(`✅ 已同步 diy_table: ${diyTable.Name}`);

  // 同步 sys_menu
  const sysMenu = await syncSysMenu(sourceConn, targetConn, diyTable);
  console.log(`✅ 已同步 sys_menu`);

  // 同步 diy_field
  const diyFields = await syncDiyField(sourceConn, targetConn, diyTable);
  console.log(`✅ 已同步 diy_field`);

  // 同步目标表结构和数据
  const exists = await checkTargetTableExists(targetConn, tableName);
  if (!exists) {
    await createTableInTarget(sourceConn, targetConn, tableName);
    await syncTableDataOnce(sourceConn, targetConn, tableName, removeField);
  } else {
    await compareAndSyncTableSchema(sourceConn, targetConn, tableName, isDeleteRedundant);
    await syncTableDataOnce(sourceConn, targetConn, tableName, removeField);
  }

  return {
    success: true,
    message: `已同步 ${tableName}`,
    diyTable,
    sysMenu,
    diyFieldsCount: diyFields.length,
    // sqlLogs 由外层统一收集
  };
}
